package top.infopub.mgr.bpa.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.bpa.BpaPublicProInfoDto;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.bpa.dao.BpaYearEffectDetailDao;
import top.infopub.mgr.bpa.dao.BpaYearEffectPlanDao;
import top.infopub.mgr.bpa.domain.YearEffectPlanDomain;
import top.infopub.mgr.bpa.dto.BpaYearEffectPlanDto;
import top.infopub.mgr.bpa.jsonVo.BpaYearEffectPlanJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.BpaYearEffectPlanService;
import top.infopub.mgr.bpa.vo.BpaYearEffectDetail;
import top.infopub.mgr.bpa.vo.BpaYearEffectPlan;
import top.infopub.mgr.bpa.vo.EffectPlanPublicVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.ProjectInfoService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.util.FileAttrUtils;
import top.infopub.mgr.util.ReflectBeanUtils;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wurz on 2021/6/20.
 */
@Service
public class BpaYearEffectPlanServiceImpl implements BpaYearEffectPlanService {
    @Resource
    private BpaYearEffectPlanDao bpaYearEffectPlanDao;

    @Autowired
    private BpaYearEffectDetailDao bpaYearEffectDetailDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private OAFlowService oaFlowService;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private BpaProcessManageService bpaProcessManageService;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Override
    public int insert(BpaYearEffectPlan bpaYearEffectPlan) {
        return bpaYearEffectPlanDao.insert(bpaYearEffectPlan);
    }

    @Override
    public int deleteByPrimaryKey(String sguid) {
        return bpaYearEffectPlanDao.deleteByPrimaryKey(sguid);
    }

    @Override
    public int delete(BpaYearEffectPlan bpaYearEffectPlan) {
        return bpaYearEffectPlanDao.delete(bpaYearEffectPlan);
    }

    @Override
    public int updateByPrimaryKey(BpaYearEffectPlan bpaYearEffectPlan) {
        return bpaYearEffectPlanDao.updateByPrimaryKey(bpaYearEffectPlan);
    }

    @Override
    public BpaYearEffectPlan selectOne(String sguid) {
        return bpaYearEffectPlanDao.selectOne(sguid);
    }

    @Override
    public Page<YearEffectPlanDomain> selectList(Page<YearEffectPlanDomain> page, EffectPlanPublicVo effectPlanPublicVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return bpaYearEffectPlanDao.selectList(effectPlanPublicVo);
    }

    @Override
    public int selectCount(BpaYearEffectPlan bpaYearEffectPlan) {
        return bpaYearEffectPlanDao.selectCount(bpaYearEffectPlan);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RspVo edit(BpaYearEffectPlanJsonVo jsonVo, Integer submitType, AuthorizationVO vo) {
        String id = jsonVo.getInfo().getId();
        BpaYearEffectPlan yearEffectPlan = new BpaYearEffectPlan();
        if (StringUtils.isNotBlank(id)) {
            //校验
            //校验数据是否存在
            BpaYearEffectPlan tmpYep = this.selectOne(id);
            if (tmpYep == null) return RspVo.getFailureResponse(400, "年度创效算数据不存在");
            //判断审批状态
            if (StringUtils.isNotBlank(tmpYep.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpYep.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpYep.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            yearEffectPlan = this.getUpdatePlanVo(jsonVo,vo);
            this.updateByPrimaryKey(yearEffectPlan);
            yearEffectPlan.setOaId(tmpYep.getOaId());
        } else {
            yearEffectPlan = this.getInsertPlanVo(jsonVo,vo);
            bpaYearEffectPlanDao.insert(yearEffectPlan);
        }
        //更新详细列表
        List<BpaYearEffectDetail> detailList = jsonVo.getYearEffectDetails();
        bpaYearEffectDetailDao.deleteByNdId(yearEffectPlan.getId());
        if (detailList != null && detailList.size() > 0) {
            for (BpaYearEffectDetail detail : detailList) {
                detail.setNdId(yearEffectPlan.getId());
                bpaYearEffectDetailDao.insert(detail);
            }
        }

        //更新附件表-MKT_PROJECT_ATTACHMENT--该处ID映射好
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(jsonVo.getFileAtt()!=null){
            String[] fileAtt = jsonVo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = FileAttrUtils.createProjectFileAtta(yearEffectPlan.getId(), file);
                attachmentList.add(attachment);
            }
        }
        //更新附件信息--根据不同类型的ProjectFileTypeEnum处理附件信息
        projectAttachmentDao.deleteByWhere(yearEffectPlan.getId(), ProjectFileTypeEnum.FILE_TYPE150.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType == 1) {
            //处理OA待办，主表里的OA_ID
            if (StringUtils.isNotBlank(yearEffectPlan.getOaId())) {
                oaFlowService.finishOA(yearEffectPlan.getOaId());
            }
            String detailJson = JSON.toJSONString(queryDetailById(yearEffectPlan.getId()));
            //根据不同类型发起不同的流程，参考BpaProcessDetailTypeEnum
            bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE32, detailJson, yearEffectPlan.getId(), yearEffectPlan.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    private BpaYearEffectPlan getUpdatePlanVo(BpaYearEffectPlanJsonVo jsonVo,AuthorizationVO auth){
        BpaYearEffectPlanDto detailObject = jsonVo.getInfo();
        BpaYearEffectPlan vo = ReflectBeanUtils.do2bo(detailObject,BpaYearEffectPlan.class);
        vo.setUptBy(auth.getId());
        vo.setUptTime(new Date());
        return vo;
    }

    private BpaYearEffectPlan getInsertPlanVo(BpaYearEffectPlanJsonVo jsonVo,AuthorizationVO auth){
        BpaYearEffectPlan temp = ReflectBeanUtils.do2bo(jsonVo.getInfo(), BpaYearEffectPlan.class);
        Date date = new Date();
        temp.setCodes(IdFactory.getUUIDUpper());
        temp.setAddBy(auth.getId());
        temp.setAddTime(date);
        temp.setUptTime(date);
        temp.setUptBy(auth.getId());
        return temp;
    }

    @Override
    public BpaYearEffectPlanJsonVo queryDetailById(String id) {
        BpaYearEffectPlanJsonVo yearEffeJson = new BpaYearEffectPlanJsonVo();
        if (StringUtils.isNotBlank(id)) {
            //id存在(详情)查询详情信息
            BpaYearEffectPlanDto yearEffeDto = new BpaYearEffectPlanDto();
            BpaYearEffectPlan plan = bpaYearEffectPlanDao.selectOne(id);
            BeanUtils.copyProperties(plan, yearEffeDto);
            BpaPublicProInfoDto proInfo = projectInfoService.queryBpaProInfoByProCode(plan.getProCode());
            BeanUtils.copyProperties(proInfo, yearEffeDto);
            //基础信息
            yearEffeJson.setInfo(yearEffeDto);

            //设置基础信息、详细列表、附件信息表
            BpaYearEffectDetail param = new BpaYearEffectDetail();
            param.setNdId(id);
            List<BpaYearEffectDetail> details = bpaYearEffectDetailDao.selectList(param);
            yearEffeJson.setYearEffectDetails(details);

            List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(id, ProjectFileTypeEnum.FILE_TYPE150.getCode(), null);
            yearEffeJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        } else {
            //查询项目列表
            yearEffeJson.setProInfoList(setupProService.queryPublicProInfo());
        }
        return yearEffeJson;
    }
}
